package com.shiyuanshenghong.web.controller.userregistercontroller;

import com.shiyuanshenghong.entity.UserModel;
import com.shiyuanshenghong.service.userregisterservice.UserRegisterService;

import com.shiyuanshenghong.util.IsActivate;

import com.shiyuanshenghong.util.MDFiveDigest;
import com.shiyuanshenghong.util.SendEMail;
import com.shiyuanshenghong.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created by LZQ on 2017/12/28.
 */
@RestController
@RequestMapping("/poverty")
public class UserRegisterController {

    @Autowired
    private UserRegisterService userRegisterService;

    @Autowired
    private MDFiveDigest mdFiveDigest;



    private UserModel userModelNew;

    /***
     * register user
     * @param userEmail
     * @param userPetName
     * @param userPassword
     * @return
     */
    @PostMapping("/register")
    public String register(@RequestParam("userEmail") String userEmail, @RequestParam("userPetName") String userPetName, @RequestParam("userPassword") String userPassword){
        userModelNew.setIsActivate(IsActivate.NOTACTIVATED.name());
        userModelNew.setUserEmail(userEmail);

        userPassword=mdFiveDigest.md5Hex(userModelNew);
        userModelNew.setUserPassword(userPassword);

        userModelNew.setUserPetName(userPetName);
        userModelNew.setUserPassword(userPassword);
        userModelNew.seteEmailActivateTime(new Date());
        UserModel userModel=userRegisterService.queryByUserEmail(userEmail);
        if(userModel==null){

            boolean flag= SendEMail.sendEmail(userEmail);
            userModelNew.setUserPassword(mdFiveDigest.md5Hex(userModelNew));
            int row=userRegisterService.addUser(userModelNew);
            if (row>0 && flag==true){
                return "账号注册成功,请激活使用!";
            }
        }else if(IsActivate.ACTIVATED.equals(userModel.getIsActivate())){
            return "该用户已经注册过了!";

        }else if("ACTIVATING".equals(userModel.getIsActivate())){

        }else if(IsActivate.NOTACTIVATED.equals(userModel.getIsActivate())){

            if((new Date()).getTime()-userModel.geteEmailActivateTime().getTime()>= Time.MILLISECOND.getText()){
                int row1=userRegisterService.deleteUser(userEmail);
                int row2=userRegisterService.addUser(userModelNew);
                return "账号注册成功!";
            }else{
                return "该邮箱已注册，还未激活，请去激活";
            }
        }
        return null;
    }

    /***
     *authentication is not activate
     */
    @GetMapping("/activateEmail")
    public void activateEmail(){
        int row=userRegisterService.updateIsActivate(userModelNew);
    }

}
